package tvv.test.catalog.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tvv.test.catalog.model.Goods;
import tvv.test.catalog.repository.GoodsRepository;
import tvv.test.catalog.util.GoodNotExist;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;


@Service
public class GoodsService implements IGoodService {

    @Autowired
    private GoodsRepository goodsRepository;

    public GoodsService() {
    }

    public GoodsService(GoodsRepository goodsRepository) {
        this.goodsRepository = goodsRepository;
    }

    @Override
    public Goods saveGoods(Goods goods) {
        return goodsRepository.save(goods);
    }

    @Override
    public Iterable<Goods> getAllGoods() {
        Iterable<Goods> allGoods = goodsRepository.findAll();
        if (allGoods != null) {
            return goodsRepository.findAll();
        } else {
            throw new NullPointerException();
        }
    }

    @Override
    public Goods getGoodsById(long id) throws IllegalArgumentException {
//        try{
//            Goods goods = goodsRepository.findOne(id);
//        }   catch (IllegalArgumentException ex) {
//            throw ex;
//        }

        if (id > 0) {
            try {
                return goodsRepository.findOne(id);
            } catch (IllegalArgumentException ex){
                throw new IllegalArgumentException();
            }

        } else {
            throw new IllegalArgumentException();
        }

    }

    @Override
    public void deleteAllGoods() {
        goodsRepository.deleteAll();
    }

    @Override
    public void deleteGoods(Goods goods) throws IllegalArgumentException {
        if (goods != null && goods.getId() > 0) {
            goodsRepository.delete(goods);
        } else {
            throw new IllegalArgumentException();
        }


//
    }

    @Override
    public long count() {
        return goodsRepository.count();
    }

}
